<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>MySQL 存储过程 | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="写在前面 什么是Mysql存储过程？ 存储过程是一组为了完成特定功能的 SQL 语句集合。MySQL 5.0 已经支持存储过程，它是数据库中最重要的功能。 本篇着重介绍一下 MySQL 创建存储过程：">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL 存储过程">
<meta property="og:url" content="https://curry3035.gitee.io/posts/13911/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="写在前面 什么是Mysql存储过程？ 存储过程是一组为了完成特定功能的 SQL 语句集合。MySQL 5.0 已经支持存储过程，它是数据库中最重要的功能。 本篇着重介绍一下 MySQL 创建存储过程：">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2020-05-27T13:58:58.000Z">
<meta property="article:modified_time" content="2022-01-07T18:58:19.621Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="MySQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/13911/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'MySQL 存储过程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-01-08 02:58:19'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">MySQL 存储过程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-05-27T13:58:58.000Z" title="发表于 2020-05-27 21:58:58">2020-05-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-01-07T18:58:19.621Z" title="更新于 2022-01-08 02:58:19">2022-01-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.9k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="MySQL 存储过程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><strong>写在前面</strong></p>
<p><font color=#008000>什么是Mysql存储过程？</font></p>
<p>存储过程是一组为了完成特定功能的 SQL 语句集合。MySQL 5.0 已经支持存储过程，它是数据库中最重要的功能。</p>
<p><strong>本篇着重介绍一下 MySQL 创建存储过程：</strong></p>
<hr>
<span id="more"></span>



<h4 id="目的"><a href="#目的" class="headerlink" title="目的"></a>目的</h4><p>将常用或复杂的工作预先用 SQL 语句写好并用一个指定名称存储起来，这个过程经编译和优化后存储在数据库服务器中，因此称为存储过程。</p>
<h4 id="优点"><a href="#优点" class="headerlink" title="优点"></a><strong>优点</strong></h4><ol>
<li><p>封装性</p>
<p>存储过程被创建后，可以在程序中被多次调用，而不必重新编写该存储过程的 SQL 语句，并且数据库专业人员可以随时对存储过程进行修改，而不会影响到调用它的应用程序源代码。</p>
</li>
<li><p>可增强 SQL 语句的功能和灵活性</p>
<p>存储过程可以用流程控制语句编写，有很强的灵活性，可以完成复杂的判断和较复杂的运算。</p>
</li>
<li><p>可减少网络流量</p>
<p>由于存储过程是在服务器端运行的，且执行速度快，因此当客户计算机上调用该存储过程时，网络中传送的只是该调用语句，从而可降低网络负载。</p>
</li>
<li><p>高性能</p>
<p>存储过程执行一次后，产生的二进制代码就驻留在缓冲区，在以后的调用中，只需要从缓冲区中执行二进制代码即可，从而提高了系统的效率和性能。</p>
</li>
<li><p>提高数据库的安全性和数据的完整性</p>
<p>使用存储过程可以完成所有数据库操作，并且可以通过编程的方式控制数据库信息访问的权限。</p>
</li>
</ol>
<h4 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h4><ol>
<li><p>如果使用大量存储过程，那么使用这些存储过程的每个连接的内存使用量将会大大增加。</p>
</li>
<li><p>存储过程的构造使得开发具有复杂业务逻辑的存储过程变得更加困难；</p>
</li>
<li><p>很难调试存储过程。只有少数数据库管理系统允许您调试存储过程。</p>
</li>
<li><p>开发和维护存储过程并不容易。</p>
<p>开发和维护存储过程通常需要一个不是所有应用程序开发人员拥有的专业技能。这可能会导致应用程序开发和维护阶段的问题。</p>
</li>
</ol>
<h4 id="创建存储过程"><a href="#创建存储过程" class="headerlink" title="创建存储过程"></a>创建存储过程</h4><p>声明语句结束符，可以自定义:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">DELIMITER $$</span><br><span class="line">或</span><br><span class="line">DELIMITER //</span><br></pre></td></tr></table></figure>

<p>声明存储过程:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">CREATE PROCEDURE demo_in_parameter(IN p_in int)       </span><br></pre></td></tr></table></figure>

<p>存储过程开始和结束符号:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">BEGIN .... END    </span><br></pre></td></tr></table></figure>

<p>变量赋值:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">SET @p_in=1  </span><br></pre></td></tr></table></figure>

<p>变量定义:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">DECLARE l_int int unsigned default 100; </span><br></pre></td></tr></table></figure>

<p>创建mysql存储过程、存储函数:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">create procedure 存储过程名(参数)</span><br></pre></td></tr></table></figure>

<p>存储过程体:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">create function 存储函数名(参数)</span><br></pre></td></tr></table></figure>



<p>举个荔枝：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">mysql&gt; delimiter $$　　#将语句的结束符号从分号;临时改为两个$$(可以是自定义) </span><br><span class="line">mysql&gt; CREATE PROCEDURE `mySun`(IN `salary` INT ,OUT sum INT)    </span><br><span class="line">	-&gt; BEGIN    </span><br><span class="line">	-&gt; 　 DECLARE a int unsigned default 10; </span><br><span class="line">	-&gt;    SET a = 100; </span><br><span class="line">	-&gt;    SET sum = Salary * a;</span><br><span class="line">	-&gt; END$$ </span><br><span class="line">Query OK, 0 rows affected (0.01 sec) </span><br><span class="line">mysql&gt; delimiter;　　#将语句的结束符号恢复为分号</span><br></pre></td></tr></table></figure>



<p>注意：</p>
<p><strong>存储过程体</strong></p>
<ul>
<li><p>存储过程体包含了在过程调用时必须执行的语句，例如：dml、ddl语句，if-then-else和while-do语句、声明变量的declare语句等</p>
</li>
<li><p>过程体格式：以begin开始，以end结束(可嵌套)</p>
</li>
<li><p>每个嵌套块及其中的每条语句，必须以分号结束，表示过程体结束的begin-end块，则不需要分号。</p>
</li>
</ul>
<h4 id="存储过程的参数"><a href="#存储过程的参数" class="headerlink" title="存储过程的参数"></a>存储过程的参数</h4><p>MySQL存储过程的参数用在存储过程的定义，共有三种参数类型,IN,OUT,INOUT,形式如：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">CREATEPROCEDURE 存储过程名([[IN |OUT |INOUT ] 参数名 数据类形...])</span><br></pre></td></tr></table></figure>

<ul>
<li>IN 输入参数：表示调用者向过程传入值（传入值可以是字面量或变量）</li>
<li>OUT 输出参数：表示过程向调用者传出值(可以返回多个值)（传出值只能是变量）</li>
<li>INOUT 输入输出参数：既表示调用者向过程传入值，又表示过程向调用者传出值（值只能是变量）</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">CREATE DEFINER=`root`@`localhost` PROCEDURE `mysun`(INOUT salary INT,INOUT sum INT)</span><br><span class="line">BEGIN</span><br><span class="line">	DECLARE a int unsigned default 10;</span><br><span class="line">	SELECT salary as &#x27;计算前的数据&#x27;;</span><br><span class="line">    SET a = 100; 	</span><br><span class="line">	SET sum = salary * a;</span><br><span class="line">	SELECT sum  as &#x27;计算后的数据&#x27;;</span><br><span class="line">END</span><br></pre></td></tr></table></figure>



<h4 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h4><h5 id="变量定义"><a href="#变量定义" class="headerlink" title="变量定义"></a>变量定义</h5><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">DECLAREvariable_name [,variable_name...] datatype [DEFAULT value];</span><br></pre></td></tr></table></figure>

<ul>
<li><code>declare</code>用于声明变量；</li>
<li><code>variable_name</code>表示变量名称；</li>
<li><code>datatype</code>为 MySQL 的数据类型；</li>
<li><code>default</code>用于声明默认值;</li>
</ul>
<p>举个荔枝:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">DECLARE l_int int unsigned default 100;   </span><br><span class="line">DECLARE l_numeric number(8,2) </span><br><span class="line">DEFAULT 9.95;   </span><br><span class="line">DECLARE l_date date DEFAULT &#x27;1999-12-31&#x27;;   </span><br><span class="line">DECLARE l_datetime datetime </span><br><span class="line">DEFAULT &#x27;1999-12-31 23:59:59&#x27;;   </span><br><span class="line">DECLARE l_varchar varchar(255) DEFAULT &#x27;This will not be padded&#x27;;</span><br></pre></td></tr></table></figure>

<h5 id="变量赋值"><a href="#变量赋值" class="headerlink" title="变量赋值"></a>变量赋值</h5><figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">SET 变量名 = 表达式值 [,variable_name = expression ...]</span><br></pre></td></tr></table></figure>

<p>举个荔枝:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">SET a = 100; </span><br></pre></td></tr></table></figure>



<h4 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h4><p>两个横杆 **–**：该风格一般用于单行注释</p>
<h4 id="控制语句"><a href="#控制语句" class="headerlink" title="控制语句"></a>控制语句</h4><h5 id="if-条件语句"><a href="#if-条件语句" class="headerlink" title="if 条件语句"></a>if 条件语句</h5><p><code>IF</code> 语句包含多个条件判断，根据结果为 <code>TRUE</code>、<code>FALSE</code>执行语句</p>
<p>定义存储过程，输入一个整数，使用 if 语句判断是正数还是负数</p>
<p>举个荔枝：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">-- 创建过程</span><br><span class="line">create procedure mypro2(in num int)</span><br><span class="line">begin</span><br><span class="line">if num&lt;0 then -- 条件开始</span><br><span class="line">select &#x27;负数&#x27;;</span><br><span class="line">elseif num=0 then</span><br><span class="line">select &#x27;不是正数也不是负数&#x27;;</span><br><span class="line">else</span><br><span class="line">select &#x27;正数&#x27;;</span><br><span class="line">end if;-- 条件结束</span><br><span class="line">end;</span><br><span class="line">-- 调用过程</span><br><span class="line">call mypro2(-1);</span><br></pre></td></tr></table></figure>



<h5 id="case-条件语句"><a href="#case-条件语句" class="headerlink" title="case 条件语句"></a>case 条件语句</h5><p><code>case</code>是另一个条件判断的语句</p>
<p>定义存储过程，输入一个整数，使用 case 语句判断是正数还是负数</p>
<p>举个荔枝：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">-- 创建过程</span><br><span class="line">create procedure mypro3(in num int)</span><br><span class="line">begin</span><br><span class="line">case -- 条件开始</span><br><span class="line">when num&lt;0 then select &#x27;负数&#x27;;</span><br><span class="line">when num=0 then select &#x27;不是正数也不是负数&#x27;;</span><br><span class="line">else select &#x27;正数&#x27;;</span><br><span class="line">end case; -- 条件结束</span><br><span class="line">end;</span><br><span class="line">-- 调用过程</span><br><span class="line">call mypro3(1);</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<h5 id="while-循环语句"><a href="#while-循环语句" class="headerlink" title="while 循环语句"></a>while 循环语句</h5><p><code>while</code>语句的用法和 <code>java</code>中的 <code>while</code>循环类似</p>
<p>定义存储过程，使用 while 循环输出 1 到 10 的累加和</p>
<p>举个荔枝：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">-- 创建过程</span><br><span class="line">create procedure mypro5(out sum int)</span><br><span class="line">begin</span><br><span class="line">declare num int default 0;</span><br><span class="line">set sum = 0;</span><br><span class="line">while num&lt;10 do -- 循环开始</span><br><span class="line">set num = num+1;</span><br><span class="line">set sum = sum+num;</span><br><span class="line">end while; -- 循环结束</span><br><span class="line">end;</span><br><span class="line">-- 调用过程</span><br><span class="line">call mypro5(@sum);</span><br><span class="line">-- 查询变量值</span><br><span class="line">select @sum;</span><br></pre></td></tr></table></figure>



<h5 id="repeat-循环语句"><a href="#repeat-循环语句" class="headerlink" title="repeat 循环语句"></a>repeat 循环语句</h5><p><code>repeat</code>语句的用法和 <code>java</code>中的 <code>do…while</code> 语句类似</p>
<p>定义存储过程，使用 repeat 循环输出 1 到 10 的累加和</p>
<p>举个荔枝：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">-- 创建过程</span><br><span class="line">create procedure mypro6(out sum int)</span><br><span class="line">begin</span><br><span class="line">declare num int default 0;</span><br><span class="line">set sum = 0;</span><br><span class="line">repeat-- 循环开始</span><br><span class="line">set num = num+1;</span><br><span class="line">set sum = sum+num;</span><br><span class="line">until num&gt;=10</span><br><span class="line">end repeat; -- 循环结束</span><br><span class="line">end;</span><br><span class="line">-- 调用过程</span><br><span class="line">call mypro6(@sum);</span><br><span class="line">-- 查询变量值</span><br><span class="line">select @sum;</span><br></pre></td></tr></table></figure>



<h5 id="loop-循环语句"><a href="#loop-循环语句" class="headerlink" title="loop 循环语句"></a>loop 循环语句</h5><p>循环语句，用来重复执行某些语句</p>
<p>执行过程中可使用 leave语句或 iterate 跳出循环，也可以嵌套 IF等判断语句。</p>
<ul>
<li><p>leave语句效果相当于 java 中的 break，用来终止循环；</p>
</li>
<li><p>iterate语句效果相当于 java 中的 continue，用来结束本次循环操作，进入下一次循环。</p>
</li>
</ul>
<p>定义存储过程，使用 loop 循环输出 1 到 10 的累加和</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">-- 创建过程</span><br><span class="line">create procedure mypro7(out sum int)</span><br><span class="line">begin</span><br><span class="line">declare num int default 0;</span><br><span class="line">set sum = 0;</span><br><span class="line">loop_sum:loop-- 循环开始</span><br><span class="line">set num = num+1;</span><br><span class="line">set sum = sum+num;</span><br><span class="line">if num&gt;=10 then</span><br><span class="line">leave loop_sum;</span><br><span class="line">end if;</span><br><span class="line">end loop loop_sum; -- 循环结束</span><br><span class="line">end;</span><br><span class="line">-- 调用过程</span><br><span class="line">call mypro7(@sum);</span><br><span class="line">-- 查询变量值</span><br><span class="line">select @sum;</span><br></pre></td></tr></table></figure>



<h4 id="存储过程的管理"><a href="#存储过程的管理" class="headerlink" title="存储过程的管理"></a>存储过程的管理</h4><p>显示存储过程</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">SHOW PROCEDURE STATUS;</span><br></pre></td></tr></table></figure>

<p>显示特定数据库的存储过程</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">SHOW PROCEDURE status where db = &#x27;test&#x27;;</span><br></pre></td></tr></table></figure>

<p>显示特定模式的存储过程，要求显示名称中包含“my”的存储过程</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">SHOW PROCEDURE status where name like &#x27;%my%&#x27;;</span><br></pre></td></tr></table></figure>

<p>显示存储过程“mypro1”的源码</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">SHOW CREATE PROCEDURE mypro1;</span><br></pre></td></tr></table></figure>

<p>删除存储过程“mypro1”</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">drop PROCEDURE mypro1;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/13911/">https://curry3035.gitee.io/posts/13911/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/MySQL/">MySQL</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/58659/" title="SpringBoot+MyBatis整合"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">SpringBoot+MyBatis整合</div></div></a></div><div class="next-post pull-right"><a href="/posts/3410/" title="JSON"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JSON</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/56511/" title="实践一下--MySQL 优化"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-04</div><div class="title">实践一下--MySQL 优化</div></div></a></div><div><a href="/posts/41767/" title="每日一面--MySQL 索引"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-05</div><div class="title">每日一面--MySQL 索引</div></div></a></div><div><a href="/posts/45802/" title="MySQL(语句)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-23</div><div class="title">MySQL(语句)</div></div></a></div><div><a href="/posts/6154/" title="MySQL(初识MySQL)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-05-23</div><div class="title">MySQL(初识MySQL)</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%AE%E7%9A%84"><span class="toc-number">1.</span> <span class="toc-text">目的</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BC%98%E7%82%B9"><span class="toc-number">2.</span> <span class="toc-text">优点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%BC%BA%E7%82%B9"><span class="toc-number">3.</span> <span class="toc-text">缺点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B"><span class="toc-number">4.</span> <span class="toc-text">创建存储过程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B%E7%9A%84%E5%8F%82%E6%95%B0"><span class="toc-number">5.</span> <span class="toc-text">存储过程的参数</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%98%E9%87%8F"><span class="toc-number">6.</span> <span class="toc-text">变量</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E5%AE%9A%E4%B9%89"><span class="toc-number">6.1.</span> <span class="toc-text">变量定义</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC"><span class="toc-number">6.2.</span> <span class="toc-text">变量赋值</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B3%A8%E9%87%8A"><span class="toc-number">7.</span> <span class="toc-text">注释</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5"><span class="toc-number">8.</span> <span class="toc-text">控制语句</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#if-%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5"><span class="toc-number">8.1.</span> <span class="toc-text">if 条件语句</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#case-%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5"><span class="toc-number">8.2.</span> <span class="toc-text">case 条件语句</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#while-%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5"><span class="toc-number">8.3.</span> <span class="toc-text">while 循环语句</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#repeat-%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5"><span class="toc-number">8.4.</span> <span class="toc-text">repeat 循环语句</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#loop-%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5"><span class="toc-number">8.5.</span> <span class="toc-text">loop 循环语句</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B%E7%9A%84%E7%AE%A1%E7%90%86"><span class="toc-number">9.</span> <span class="toc-text">存储过程的管理</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>